(function () {/**
 * Created by ChenJiangwei on 2017/1/20.
 */
var commonObject = function() {
    // this.globalHost='http://121.40.178.164:4040/agent-service';
    this.globalHost='http://wxgzht.esheyi.com/agent-service';
    // this.globalHost='http://192.168.1.127:8080/agent-service';
    // this.globalHost='http://121.40.201.35:4040/agent-service';
    // this.globalHost='http://120.55.66.146:8080/agent-service';
    this.imageHost='http://wxgzht.esheyi.com';
    // this.imageHost='http://121.40.178.164:4040';
    // this.imageHost='192.168.1.127:8080';
    // this.imageHost='http://121.40.201.35:4040';
    // this.imageHost='http://120.55.66.146:8080';
    this.registerPort='/api/agent/register.do';
    this.registerMorePort='/api/agent/registerMore.do';
    this.sendSMSPort='/api/agent/sendSMS.do';
    this.loginPort='/api/agent/login.do';
    this.validatePort='/api/agent/validate.do';
    this.resetPWPort='/api/agent/resetPW.do';
    this.updateAgentInfoPort='/api/agent/updateAgent.do';
    this.saveFeedbackPort='/api/agent/saveFeedback.do';
    this.getCompanyListPort='/api/agent/getCompanyList.do';
    this.getStoreListPort='/api/agent/getStoreList.do';
    this.getAgentDetailPort='/api/agent/getDetail.do';
    this.submitHousePort='/api/agentHouse/saveHouseInfo.do';
    this.getHouseListPort='/api/agentHouse/getHouseList.do';
    this.uploadBasePort='/api/upload/uploadBase64.do';
    this.getCurrentWeekHouseCount='/api/agent/getCurrentWeekHouseCount.do';//获取本周提交房源数量
    this.getHouseCountByAgent='/api/agent/getHouseCountByAgent.do';//获取历史提交房源数量
    this.getRewardAttentionInfoListByAgentId='/api/reward/getRewardAttentionInfoListByAgentId.do';//关注列表
    this.getRewardViewInfoListByAgentId='/api/reward/getRewardViewInfoListByAgentId.do';//查看记录列表
    this.getRewardList='/api/reward/getRewardList.do';//悬赏信息列表
    this.getRewardHouseList='/api/reward/getRewardHouseList.do';//悬赏列表带筛选
    this.getRewardDetail='/api/reward/getRewardDetail.do';//悬赏信息详情
    this.attention='/api/reward/attention.do';//关注接口
    this.uncover='/api/reward/uncover.do';//刮奖接口
    this.getByParamKey='/api/systemConf/getByParamKey.do';//banner
    this.getBannerList='/api/bannerInfo/getBannerList.do';//带链接的banner传参数{paramKey:'banner',token:token}
    this.getZoneList='/api/zone/getZoneListByLevel.do';//区域数据接口
    this.getLineList='/api/trafficLine/getLineList.do';//地铁数据接口
    this.openLock='/api/lock/openLock.do';//一键开锁接口
    this.getLockOpenList='/api/lock/getLockOpenList.do';//获取开锁列表
    this.addHouseVisitInfo='/api/reward/addHouseVisitInfo.do';//上传带看
    this.getVisitPointByAgentId='/api/agent/getVisitPointByAgentId.do';//获取积分
    this.getHouseVisitList='/api/reward/getHouseVisitList.do';//获取带看列表
    this.pointExchange='/api/agent/pointExchange.do';//积分提现
    this.getPointExchangeList='/api/agent/getPointExchangeList.do';//积分提现列表
    this.getSignture='/api/WeChat/getSignture.do';//获取微信签名
    this.getHouseVisitListByHouseId='/api/reward/getHouseVisitListByHouseId.do';//获取该房源被带看列表；
    this.perfectAgentInfo='/api/agent/perfectAgentInfo.do';//个人资料编辑；
    this.popularApp=['MQQBrowser'];
    this.dialog=$('#dialogErr');
    this.goBack=$('#topbar').children('.back');
};
commonObject.prototype = {
    getQueryString:function(name) {
        var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)");
        var r = window.location.search.substr(1).match(reg);
        if (r != null) return decodeURI(r[2]);
        return null;
    },
    checkApp:function(){
        var self=this;
        var result="";
        $.each(self.popularApp,function(idx,ele){
            if(navigator.userAgent.indexOf(ele)>-1){
                result=true;
                return;
            }
        });
       return result;
    },
    //显示弹框
   errDialog:function(msg){
        var self=this;
        self.dialog.removeClass('mask-hide').addClass('mask-show').html(msg);
        setTimeout(function() {
            self.dialog.removeClass('mask-show').addClass('mask-hide').html('');
        }, 3000);
    },
    isInWX:function(){
        var slef=this;
        if(navigator.userAgent.indexOf('MQQBrowser')>-1){
            return true;
        }
        return false;
    },
    getYearMonthAndDay:function(time){
        var format=time.replace(/[-.]/g,"/");
        var dateFormat=new Date(format);
        var fullYear = dateFormat.getFullYear();
        var month = dateFormat.getMonth()+1;
        month=month<9?'0'+month:month;
        var day = dateFormat.getDate();
        day=day<9?'0'+day:day;
        var yearMonthAndDay=fullYear+"/"+month+"/"+day;
        return yearMonthAndDay;
    },
    getSendDataByForm: function(selector) {
        var list = $(selector).serializeArray(),
            json = {};
        $.each(list, function(i, I) {
            var tag = $(selector).find('[name=' + I.name + ']')[0].tagName;
            if(tag === 'TEXTAREA') {
                I.value = I.value.replace(/\r\n/g, "\\r\\n");
            }
            if (!json[I.name]) {
                json[I.name] = I.value
            } else {
                json[I.name] = json[I.name] + ',' + I.value;
            }
        });
        return json;
    },
    requestFormData:function (options) {
        var self=this;
        var url=options.url;
        var sendData=options.sendData;
        var resSuccess=options.resSuccess;
        var resFailed=options.resFailed;
        var resError=options.resError;
        jQuery.support.cors = true;
        $.ajax
        ({
            data:sendData,
            type: "POST",
            contentType: "application/x-www-form-urlencoded;charset=utf-8",
            dataType:"json",
            url:url,
            success:function(data){
                if(typeof data==="string"){
                    data=JSON.parse(data);
                }
                if(!!data && data['code']=="0"){
                    sendData={};
                     !!resSuccess&&$.isFunction(resSuccess)&&resSuccess(data);
                }else{
                    !!resFailed&&$.isFunction(resFailed)&&resFailed(data);
                    if(data.code==101 ||data.code==102){
                        console.log("token为空或者token失效");
                        window.location.href='login.html';
                    }
                }
            },
            timeout:10000,
            error: function (XMLHttpRequest, textStatus, errorThrown) {
                self.errDialog("网络不畅，请稍后重试");
                !!resError&&$.isFunction(resError)&&resError();
            }
        });
    },
    getToken: function() {
        var self=this;
        var loginData = self.getLocalData("H5-agentInfo");
        if (!loginData) {
            window.location.href = './login.html';
            return false;
        }
        if (!loginData.token) {
            window.location.href = './login.html';
            return false;
        }
        return loginData.token;
    },
    setLocalStorage: function(key, value) {
        if (window.localStorage) {
            localStorage.setItem(key, value);
        }
    },
    setSessionStorage: function(key, value) {
        if (window.sessionStorage) {
            sessionStorage.setItem(key, value);
        }
    },
    getLocalData: function(key) {
        if (window.localStorage) {
            var data = localStorage.getItem(key);
            if (!data) {
                window.location.href = './login.html';
                return false;
            }
            data = JSON.parse(data);
            return data;
        }
    },
    getSessionData: function(key) {
        if (window.sessionStorage) {
            var data = sessionStorage.getItem(key);
            data = JSON.parse(data);
            return data;
        }
    },
    buildNormalSwipe:function (options) {
        var self=this;
        //获取相关dom元素
        var $sliderPanel=$(options.sliderPanel);
        var slideWidth=$sliderPanel.width();//获取屏幕宽度值
        //获取轮播图容器
        var $sliderUl=options.sliderContainer?$(options.sliderContainer):$sliderPanel.find(".slider").length>0?$sliderPanel.find(".slider"):$sliderPanel.find("ul");
        //获取计数点
        var $countingOl=options.sliderCounting?$(options.sliderCounting):$sliderPanel.find(".counting").length>0?$sliderPanel.find(".counting"):$sliderPanel.find("ol");
        //判断是否有计数点
        var hasCounting=$countingOl.length||0;
        var dataType=options.dataType||"image";//轮播图片类型，背景，图片。。。
        var countingType=options.countingType||"point";
        var imgPath=options.imgPath||"";//图片的目录
        var data=options.data||[]; // 图片的数据源

        var delayTime=parseInt(options.moveDelay)||2000;//获取设置轮播图的间隔时间,默认是2s
        var dataLength=data.length||0; // 图片数据源的长度
        var sliderItemsLength=dataLength+2; //轮播图内的轮播项数量
        var $ImagesWidth=sliderItemsLength*100; //计算轮播图容器的宽度
        $sliderUl.css({'width':($ImagesWidth+"%")});//设置轮播容器的宽度
        //声明空数组，sliderItems放置轮播图的每一项图片，countingItems计数用来统计
        var sliderItems=[];
        var countingItems=[];
        var index=1;//获取当前默认计数的索引
        //遍历数据源，组装数据
        if (dataLength) {
            if(dataType==='background'){
                if(hasCounting && countingType === "point"){
                    buildPointCountingByBackground(data);
                    setPointCountingStyleByImage();
                }
                if(hasCounting && countingType === "number"){
                    buildNumberCountingByBackground(data);
                    setNumberCountingStyleByImage();
                }
            }
            if(dataType==='image'){
                if(hasCounting && countingType === "point"){
                    buildPointCountingByImage(data);
                    setPointCountingStyleByImage();
                }
                if(hasCounting && countingType === "number"){
                    buildNumberCountingByImage(data);
                    setNumberCountingStyleByImage();
                }
            }
            if(dataType==='DOM'){
                if(hasCounting && countingType === "point"){
                    buildPointCountingByDOM(data);
                    setPointCountingStyleByDOM();
                }
                if(hasCounting && countingType === "number"){

                }
            }
            sliderItems.unshift(sliderItems[sliderItems.length-1]);
            sliderItems.push(sliderItems[1]);
            //为轮播容器内添加dom结构，并设置每一项的宽度
            $sliderUl.html(sliderItems.join(""));
            $sliderUl.css('left',-index*slideWidth+"px");
            //noinspection JSValidateTypes
            var $sliderLis = $sliderUl.children("li");
            $sliderLis.css({'width': (100 / sliderItemsLength + "%")});

        }
        var timer=null;
        autoMove();
        //noinspection JSValidateTypes
        var $countingLis=$countingOl.children("li");

        $sliderUl.on("transitionend",function () {
            index=index>=dataLength+1?1:index;
            index=index <=0?dataLength:index;
            self.removeTransition($sliderUl,"trans");
            self.moveColumn($sliderUl,-index * slideWidth);
            if(hasCounting && countingType === "point"){

                $countingLis.eq(index-1).addClass("now").siblings("li").removeClass("now");
            }
            if(hasCounting && countingType === "number"){
                $("#current-index").html(index);
            }
        });
        var start = 0;
        var end = 0;
        var distanceFinal = 0;
        var move = 0;
        var moveDistance=0;

        $sliderUl.on('touchstart', function(e) {
            e.stopPropagation();
            // e.preventDefault();
            timerChecked(timer);
            self.removeTransition($sliderUl,"trans");
            start=e.touches[0].clientX;
        });

        $sliderUl.on('touchmove', function(e) {
            e.stopPropagation();
            e.preventDefault();
            move=e.touches[0].clientX;
            moveDistance = move - start;
            index=index>=dataLength+1?1:index;
            index=index <=0?dataLength:index;
            var num = moveDistance + -index * slideWidth;

            self.removeTransition($sliderUl,"trans");
            self.moveColumn($sliderUl,num);
        });
        $sliderUl.on('touchend', function(e) {
            e.stopPropagation();
            // e.preventDefault();
            end = e.changedTouches[0].clientX;
            distanceFinal = end - start;
            if (Math.abs(distanceFinal) > (slideWidth * 1 / 5)) {
                if (distanceFinal < 0) {
                    index++;
                } else {
                    index--;
                }
            }
            self.moveColumn($sliderUl,-index * slideWidth);
            self.addTransition($sliderUl,"trans");
            autoMove();
        });
        //tools//linkAddress和picturePath可定义成全局变量，进行传参数
        function buildPointCountingByDOM(data) {
            $.each(data, function (idx, ele) {
                // sliderItems.push('<li>'+ele+'</li>');
                var type=typeof ele;
                if(type =='string'){
                    sliderItems.push('<li>'+ ele +'"></li>');
                }else if(type == 'object'){
                    if(ele["linkAddress"]){
                        sliderItems.push('<li>'+
                            '<a href="'+(ele["linkAddress"].indexOf("http://")>-1?ele["linkAddress"]:"http://"+ele["linkAddress"])+'"></a>'+
                            '</li>');
                    }else {
                        sliderItems.push('<li>'+ele['picturePath']+'</li>');
                    }
                }
                countingItems.push("<li></li>");
            });
        }

        function buildNumberCountingByBackground(data) {
            $.each(data, function (idx, ele) {
                var type=typeof ele;
                if(type =='string'){
                    sliderItems.push('<li style="background-image:url('+ imgPath + ele+')"></li>');
                }else if(type == 'object'){
                    if(ele["linkAddress"]){
                        sliderItems.push('<li style="background-image:url('+ imgPath + ele['picturePath']+')">'+
                            '<a href="'+(ele["linkAddress"].indexOf("http://")>-1?ele["linkAddress"]:"http://"+ele["linkAddress"])+'"></a>'+
                            '</li>');
                    }else {
                       sliderItems.push('<li style="background-image:url('+ imgPath + ele['picturePath']+')"></li>');
                    }
                }
                // sliderItems.push('<li style="background-image:url('+ imgPath + ele+')"></li>');
            });
            countingItems.push("<li><span id='current-index'>"+index+"</span> / <span id='total-count'>"+dataLength+"</span></li>");
        }

        function buildPointCountingByBackground(data) {
            $.each(data, function (idx, ele) {
                var type=typeof ele;
                if(type =='string'){
                    sliderItems.push('<li style="background-image:url('+ imgPath + ele+')"></li>');
                }else if(type == 'object'){
                    if(ele["linkAddress"]){
                        sliderItems.push('<li style="background-image:url('+ imgPath + ele['picturePath']+')">'+
                            '<a href="'+(ele["linkAddress"].indexOf("http://")>-1?ele["linkAddress"]:"http://"+ele["linkAddress"])+'"></a>'+
                            '</li>');
                    }else {
                       sliderItems.push('<li style="background-image:url('+ imgPath + ele['picturePath']+')"></li>');
                    }
                }
                // sliderItems.push('<li style="background-image:url('+ imgPath + ele+')"></li>');
                countingItems.push("<li></li>");
            });
        }

        function buildPointCountingByImage(data) {
            $.each(data, function (idx, ele) {
                var type=typeof ele;
                if(type =='string'){
                    sliderItems.push('<li><img src="' + imgPath + ele + '"></li>');
                }else if(type == 'object'){
                    if(ele["linkAddress"]){
                        sliderItems.push('<li>'+
                            '<a href="'+(ele["linkAddress"].indexOf("http://")>-1?ele["linkAddress"]:"http://"+ele["linkAddress"])+'">'+
                                '<img src="' + imgPath + ele['picturePath'] + '">'+
                            '</a>'+
                            '</li>');
                    }else {
                        sliderItems.push('<li><img src="' + imgPath + ele['picturePath'] + '"></li>');
                    }
                }
                countingItems.push("<li></li>");
            });
        }

        function buildNumberCountingByImage(data) {
            $.each(data, function (idx, ele) {
                var type=typeof ele;
                if(type =='string'){
                    sliderItems.push('<li><img src="' + imgPath + ele + '"></li>');
                }else if(type == 'object'){
                    if(ele["linkAddress"]){
                        sliderItems.push('<li>'+
                            '<a href="'+(ele["linkAddress"].indexOf("http://")>-1?ele["linkAddress"]:"http://"+ele["linkAddress"])+'">'+
                                '<img src="' + imgPath + ele['picturePath'] + '"></a>'+
                            '</li>');
                    }else {
                        sliderItems.push('<li><img src="' + imgPath + ele['picturePath'] + '"></li>');
                    }
                }
                // sliderItems.push('<li><img src="' + imgPath + ele + '"></li>');
            });
            countingItems.push("<li><span id='current-index'>"+index+"</span> / <span id='total-count'>"+dataLength+"</span></li>");
        }

        function setPointCountingStyleByImage() {
            //为轮播计数添加dom结构，并初始化当前默认的计数点
            $countingOl.addClass("point").html(countingItems.join(""));
            var countingOlWidth=$countingOl.width();//获取计数点ol的宽度
            //noinspection JSValidateTypes
            var $countingLis=$countingOl.children("li");
            var unitPointWidth=$countingLis.width();
            var unitPointMargin=((countingOlWidth/dataLength)-unitPointWidth)/2;
            $countingLis.css({margin:"0 "+unitPointMargin+"px"});
            $countingLis.eq(0).addClass('now');
        }

        function setNumberCountingStyleByImage() {
            $countingOl.addClass("number-counting").html(countingItems.join(""));
        }
        function setPointCountingStyleByDOM() {
            $countingOl.addClass("point").html(countingItems.join(""));
            //noinspection JSValidateTypes
            $countingOl.children("li").eq(0).addClass('now');
        }

        function autoMove() {
            timerChecked();
            if(delayTime>=0 && !!options.autoPlay){
                timer = setInterval(function () {
                    index++;
                    self.addTransition($sliderUl,"trans");
                    self.moveColumn($sliderUl,-index * slideWidth);
                },delayTime);
            }
            return false;
        }
        function timerChecked() {
            return !!timer?clearInterval(timer):null;
        }
    },
    removeTransition:function (selector,className) {
        $(selector).removeClass(className);
    },
    addTransition:function (selector,className) {
        var selfSelector=$(selector);
        if(!selfSelector.hasClass(className)){
            selfSelector.addClass(className);
        }
    },
    moveColumn:function (selector,num) {
        num=(num+"").indexOf("%")>-1?num:num+"px";
        $(selector).css('left',num);
    },
    moveRow:function (selector,num) {
        num=(num+"").indexOf("%")>-1?num:num+"px";
        $(selector).css('top',num);
    },
    goBackNext:function(){
        var self=this;
        self.goBack.off('touchend').on("touchend", function (e) {
            e.preventDefault();
            e.stopPropagation();
            window.history.back();
        });
    }
};
window.common = new commonObject();
}).call(this);